<template>
    <div class="main-contain" style="width: 980px;">
      <!-- 搜索筛选 -->
      <p class="page-title">我的订单</p><!--{{ needInfo.title }}-->
      <!-- <el-form :inline="true" :model="formInline" class="user-search">
        <el-form-item label="搜索：">
          <el-input size="small" v-model="formInline.kw" placeholder="输入标题"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" icon="el-icon-search" @click="search" class="black-button">搜索</el-button>
        </el-form-item>
      </el-form> -->
      <!--列表-->
      <el-table v-loading="loading" :data="listData" border element-loading-text="拼命加载中">
        <el-table-column align="center" label="订单编号" prop="orderCode"></el-table-column>
        <el-table-column align="center" label="订单时间" width="140">
          <template #default="scope">
            <div>{{timestampToDayHM(scope.row.orderTime)}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="orderTitle" label="商品信息" width="300">
          <template #default="scope">
            <div>
              <el-avatar shape="square" size="medium" :src="scope.row.product.mainPic"></el-avatar>
              <span class="opname">{{ scope.row.product.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="price" label="消耗积分">
          <template #default="scope">
            <span class="price">{{ scope.row.totalPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="status" label="订单状态">
          <template #default="scope">
            <el-tag size="small" type="danger" v-if="scope.row.status==1">待发货</el-tag>
            <el-tag size="small" type="success" v-if="scope.row.status==2">已发货</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="操作" width="240">
          <template #default="scope">
            <el-button size="mini" v-if="scope.row.status==1" class="green-button" @click="onShowPay(scope.row)">支付</el-button>
            <el-button size="mini" v-if="scope.row.status==1" type="danger" @click="onCancel(scope.row.orderId)">取消</el-button>
            <el-button size="mini" v-if="scope.row.status==3" class="orange-button" @click="onFinish(scope.row.orderId)">确认收货</el-button>
            <el-button size="mini" class="green-button" @click="showDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <!-- 分页组件 -->
      <el-pagination background layout="prev, pager, next" v-model:page-size="queryForm.pageSize" v-model:current-page="queryForm.pageNo" :total="total" @current-change="getInfo" />
      
      <!--支付对话框-->
      <el-dialog
        title="支付"
        v-model="payVisible"
        width="60%"
        :close-on-click-modal=false
        :show-close="false"
      >
        <el-descriptions class="margin-top" :column="2" border>
            <el-descriptions-item label="订单编号">{{orderInfo.orderCode}}</el-descriptions-item>
            <el-descriptions-item label="订单金额">
            ￥
            <span style="font-size: 22px; color: #d4571d;">
                {{ formatAmount(orderInfo.totalPrice) }}
            </span>
            </el-descriptions-item>
            
        </el-descriptions>
        <div class="pay-btn">
            <div class="qr-code">
            <img src="http://129.211.222.131:18080/images/pay.png" alt="" style="width: 200px;height: 200px;">
            </div>
            <el-button size="mini" icon="Close" type="info" @click="closeDialog()">取消</el-button>
            <el-button size="mini" icon="Check" type="primary" @click="onPay()">已支付</el-button>
        </div>
      </el-dialog>
  
      <!--详情对话框-->
      <el-dialog v-model="detailVisible" :title="title" width="60%" append-to-body :close-on-click-modal="false">
        <el-descriptions class="margin-top" :column="2" border v-if="orderInfo">
            <el-descriptions-item label="订单提交时间" labelStyle="width: 160px;">{{ timestampToDayHM(orderInfo.orderTime) }}</el-descriptions-item>
            <el-descriptions-item label="订单号" labelStyle="width: 160px;">{{ orderInfo.orderCode }}</el-descriptions-item>
            <el-descriptions-item label="订单总额" labelStyle="width: 160px;">
              <span style="color:#888;font-size:12px;">￥</span>
              <strong class="price">{{formatAmount(orderInfo.totalPrice)}}</strong>
            </el-descriptions-item>
            <el-descriptions-item label="订单状态" labelStyle="width: 160px;">
              <el-tag type="warning" v-if="orderInfo.status==1">待支付</el-tag>
              <el-tag type="primary" v-if="orderInfo.status==2">已支付待发货</el-tag>
              <el-tag type="success" v-if="orderInfo.status==3">已发货</el-tag>
              <el-tag type="info" v-if="orderInfo.status==4">已完成</el-tag>
              <el-tag type="info" v-if="orderInfo.status==-1">已取消</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="客户备注" labelStyle="width: 160px;" v-if="orderInfo.remark">{{ orderInfo.remark }}</el-descriptions-item>
            <el-descriptions-item label="快递单号" labelStyle="width: 160px;" v-if="orderInfo.expNo">{{ orderInfo.expNo }}</el-descriptions-item>
        </el-descriptions>
        <div class="product-items">
          <ul>
            <li class="pite" v-for="(pitem, idx) in orderInfo.orderItems" :key="idx">
              <div class="pimg">
                <img :src="pitem.product.mainPic" alt="">
              </div>
              <div class="pdesc">
                <p>{{ pitem.product.name }}</p>
                <p>数量：{{ pitem.quantity }}</p>
                <p>单价：￥<span class="price">{{ formatAmount(pitem.price) }}</span></p>
                <p class="subtitle">{{ pitem.product.subTitle }}</p>
                <el-button v-if="pitem.iscomment==0 && orderInfo.status==4" size="small" icon="ChatLineSquare" type="primary" 
                  @click="showFeedback(pitem)">评论</el-button>
              </div>
            </li>
          </ul>
        </div>
      </el-dialog>
  
      <el-dialog
        title="商品评论"
        v-model="editFormVisible"
        width="40%"
      >
        <el-form
          label-width="120px"
          :model="editForm"
          ref="formRef"
        >
          <el-form-item label="评论内容">
            <el-input
              size="small"
              v-model="editForm.content"
              type="textarea"
              :row="3"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="closeCommDialog">取消</el-button>
            <span style="padding: 0 5px;"></span>
            <el-button
              type="primary"
              class="title"
              @click="onPublishComment()"
              >确定</el-button
            >
          </div>
        </template>
      </el-dialog>
    </div>
</template>
<script setup lang="ts">
  import { ref, reactive, nextTick, toRef } from "vue";
  import baseService from "@/service/baseService";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { timestampToDayHM, timestampToHM, timestampToDate, formatAmount } from "@/utils/utils"
  import { fileUploader } from '@/utils/upload.js'
  import { useRouter, useRoute } from 'vue-router'
  
  // 查询参数
  const queryForm = reactive({
      deptName: "",
      pageNo: 1,
      pageSize: 10
  });
  const router = useRouter();
  const route = useRoute();
  // 列表内容数量
  const total = ref(0);
  // 列表是否加载
  const loading = ref(true);
  // 列表返回值
  const listData = ref<any[]>([]);
  
  // 表单实例
  const formRef = ref();
  const addressRef = ref();
  // 是否打开弹出框
  const open = ref(false);
  const payVisible = ref(false);
  const detailVisible = ref(false);
  const addressFormopen = ref(false);
  const editFormVisible = ref(false);
  // 弹出框标题
  const title = ref("");
  const addressList = ref<any[]>([]);
  const orderInfo = ref();

  // 表单验证
  const rules = ref({
      deptName: [{ required: true, message: "规则名称不能为空", trigger: "blur" }],
  });
  
  // 订单表单数据
  let editForm = toRef(
    reactive({
      content: '',
      itemId: '',
      productId: ''
    })
  )
  
  function onCancel(orderId: number){
    ElMessageBox.confirm("确认要取消该订单吗?", "提示").then(() => {
      baseService.get(`/admin/order/cancel/${orderId}`).then((res) => {
        if (res.code === 200) {
          ElMessage.success("订单已取消")
          getInfo()
        }else{
          ElMessage.warning("取消失败")
        }
      });
    })
  }

  //确认收货
  function onFinish(orderId: number){
    ElMessageBox.confirm("是否确认收货?", "提示").then(() => {
      baseService.get(`/api/order/complete/${orderId}`).then((res) => {
        if (res.code === 200) {
          ElMessage.success("订单已完成")
          getInfo()
        }else{
          ElMessage.warning("请求失败")
        }
      });
    })
  }

  function onShowPay(data:any){
    console.log('EEEE', data)
    orderInfo.value=data
    payVisible.value = true
  }

  //显示详情
  function showDetail(data){
    detailVisible.value = true;
    title.value = "订单详情";
    console.log('订单详情',data)
    orderInfo.value = data
  }

  function showFeedback(data){
    editFormVisible.value = true;
    console.log('WWWWWWWW', data)
    editForm.value.itemId = data.itemId
    editForm.value.productId = data.productId
  }

  function closeDialog(){
    payVisible.value = false
  }

  function closeCommDialog(){
    editFormVisible.value = false
  }
  
  //支付，完成订单
  const onPay = ()=>{
    let orderCode = orderInfo.value.orderCode
    baseService.get(`/api/order/pay/${orderCode}`).then((res) => {
        loading.value = false;
        ElMessage.success("支付成功");
        payVisible.value=false
        getInfo()
    }).catch(() => {
      ElMessage.error("支付异常");
        loading.value = false;
    });
  }
  
  function onNewAdd(){
      addressFormopen.value = true
      console.log('NNNNNNNNNNN')
  }
  
  //获取订单列表
  const getInfo = () => {
    baseService.post(`/api/order/myorders`, queryForm).then((res) => {
      console.log('获取订单列表：',res)
      listData.value = res.data.records;
      total.value = res.data.totalrecord;
      loading.value = false;
    }).catch(() => {
        loading.value = false;
    });
  }
  
  const onPublishComment = ()=>{
    console.log('EEEEEEEEEE')
    baseService.post(`/api/order/feedback/save`, editForm.value).then((res) => {
        loading.value = false;
        ElMessage.success('评论成功');
        editFormVisible.value = false
        detailVisible.value = false
        getInfo()
      }).catch(() => {
          loading.value = false;
      });
  }
  
  //提交订单
  const submitOrder = ()=>{
    baseService.post(`/api/order/save`, editForm.value).then((res) => {
        loading.value = false;
        ElMessage.success('订单已提交，请支付');
        payVisible.value = true
      }).catch(() => {
          loading.value = false;
      });
  }
  
  getInfo();
</script>

<style scoped>
.page-title {
    font-size: 16px;
    font-weight: bold;
    color: #0038a7;
    padding-left: 5px;
    border-left: 3px solid #0038a7;
    margin: 15px 0;
    height: 30px;
    line-height: 30px;
}
.main-contain .el-button{
  margin-left: 2px;
}
.dtitle{
  font-size: 16px;
  margin: 10px 0;
  color: #666;
}
.introduction{
  margin: 15px 0;
}
.price{
  color: #d77f57;
}
.show-btn{
  text-align: center;
  margin-top: 100px;
  clear: both;
}
.opname{
  vertical-align: top;
}
.qr-code, .pay-btn{
  text-align: center;
}
.qr-code{
  margin: 12px 0;
}
.order-item{
  line-height: 36px;
  border-bottom: 1px solid #ebeef5;
  padding-top: 10px;
}
.main-contain .order-item .el-button{
  margin-left: 15px;
  vertical-align: top;
}
.green-button{
  background-color: #00aeec !important;
  border: 1px solid #00aeec;
  color: #fff !important;
  margin: 0 2px;
}
.green-button:HOVER{
  background-color: #29d !important;
  border: 1px solid #29d;
}
.orange-button{
    margin: 0 2px;
  background-color: #e2a388 !important;
  border: 1px solid #ccc;
  color: #fff !important;
}
.orange-button:HOVER{
  background-color: #e2a388 !important;
  border: 1px solid #fff;
}
.pra-info p{
  margin: 0;
}
.product-items{
  padding: 10px 0;
}
.product-items li{
  border-bottom: 1px solid #ccc;
  margin-bottom: 5px;
}
.product-items .pite{
  clear: both;
  height: 125px;
}
.product-items .pimg{
  float: left;
  width: 140px;
  overflow: hidden;
}
.product-items .pimg img{
  width: 100%;
  height: 120px;
}
.product-items .pdesc{
  float: left;
  padding: 4px 10px;
}
.product-items .pdesc p{
  margin: 0;
  padding: 2px 0;
}
.product-items .pdesc .subtitle{
  font-size: 12px;
}
.price{
  color:#F56C6C;
}
</style>